/**
 * darwing         2020/7/15
 */


window.onload = function() {
    var darwingLineObj = {
        cavs: $('.cavs'),
        context: $('.cavs')[0].getContext('2d'),
        color: $('input:eq(0)'),
        cleanBoard: $('input:eq(1)'),
        eraser: $('input:eq(2)'),
        res: $('input:eq(3)'),
        range: $('input:eq(4)'),
        flag: null,
        arrImg: [],
        init: function() {
            this.context.lineCap = 'round'; //线条起始开始的样式 是圆的
            this.context.lineJoin = 'round'; //线条转弯的时候的样式
            this.draw();
            this.btnFn();
        },
        draw: function() {
            var cavs = this.cavs,
                self = this;
            var c_x = cavs.offset().left,
                c_y = cavs.offset().top;

            cavs.mousedown(function(e) {
                self.flag = true;
                e = e || window.event;
                var m_x = e.pageX - c_x,
                    m_y = e.pageY - c_y;
                self.context.beginPath();
                self.context.moveTo(m_x, m_y);
                cavs.mousemove(function(e) {
                    if (self.flag) {
                        self.context.lineTo(e.pageX - c_x, m_y = e.pageY - c_y);
                        self.context.stroke();
                    }
                });
                cavs.mouseup(function() {
                    self.flag = false;
                });
                cavs.mouseleave(function() {

                    self.flag = false;
                });
                var imgData = self.context.getImageData(0, 0, self.cavs[0].width, self.cavs[0].height);
                self.arrImg.push(imgData);
                // console.log(arrImg);
                //console.log(self.arrImg);
            });
        },
        btnFn: function() {
            var self = this;
            $('.btn-list').on('click', function(e) {
                e = e || window.event;
                switch (e.target.value) {
                    case '清屏':
                        self.context.clearRect(0, 0, self.cavs[0].width, self.cavs[0].height)
                        break;
                    case '橡皮':
                        self.context.strokeStyle = 'antiquewhite';
                        break;
                    case '撤销':
                        if (self.arrImg.length > 0) {
                            self.context.putImageData(self.arrImg.pop(), 0, 0);
                        }
                        break;

                }
            });
            this.color.change(function(e) { //颜色变化的时候
                self.context.strokeStyle = $(this).val();
                console.log(88);
            });
            this.range.change(function(e) {
                self.context.lineWidth = $(this).val();
            })
        }
    }

    darwingLineObj.init();

}